import os

from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework.response import Response
from rest_framework.permissions import IsAdminUser
from rest_framework.viewsets import ModelViewSet
from meiduo_admin.serializers.skus import GoodsCategorySerializer
from goods.models import SPU, Brand, GoodsCategory
from meiduo_admin.serializers.spus import SPUSerializer
from meiduo_admin.utils import PageNum
from meiduo_admin.serializers.brands import BrandSerializer

class SPUView(ModelViewSet):
    #指定序列化器
    serializer_class = SPUSerializer
    # 指定查询集
    queryset = SPU.objects.all()
    # 权限
    permission_classes = [IsAdminUser]
    # 分页
    pagination_class = PageNum

    # 获取商品分类
    def brands(self,request):
        data = Brand.objects.all()
        ser = BrandSerializer(data,many=True)
        return Response(ser.data)

    # 获取一级分类
    def categories(self,reqeust):
        data = GoodsCategory.objects.filter(parent=None)
        ser = GoodsCategorySerializer(data,many=True)
        return Response(ser.data)
    # 获取二级和三级分类
    def categories_child(self,reqeust,pk):
        data = GoodsCategory.objects.filter(parent=pk)
        ser = GoodsCategorySerializer(data,many=True)
        return Response(ser.data)
    # 保存上传图片
    def image(self,request):
        # 初始化生成连接对象
        client=Fdfs_client(os.path.join(settings.BASE_DIR,'utils/fasfdfs/client.cong'))
        # 获取图片数据
        image = request.data.get('image')
        # 上传图片
        res = client.upload_by_buffer(image.read())
        # 判断图片是否上传成功
        if res['Status']!='Upload successed.':
            return Response({'error':'上传失败'})
        # 将图片保存在fastdfs中连接地址保存在图片中
        image_path = res['Remote file_id']
        image_url = 'http://127.0.0.1:8000/'+image_path
        return Response({'img_url':image_url})































